package com.lagou.edu.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Component
@RefreshScope
public class IpRegisterFilter implements GlobalFilter, Ordered {

    @Value("${gateway.register.max.count}")
    private Integer registerMaxCount;

    @Value("${gateway.register.interval.time}")
    private Integer registerIntervalTime;

    private ConcurrentHashMap<String, List<Long>> ipCacheMap = new ConcurrentHashMap<>();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getPath().toString();
        if (!path.startsWith("/api/user/register")) {
            return chain.filter(exchange);
        }

        long currentTime = System.currentTimeMillis();
        String clientIp = Objects.requireNonNull(request.getRemoteAddress()).getHostString();
        List<Long> timeList = ipCacheMap.get(clientIp);
        if (CollectionUtils.isEmpty(timeList)) {
            timeList = new ArrayList<>();
        }

        int count = 0;
        Iterator<Long> iterator = timeList.iterator();
        if (iterator.hasNext()) {
            Long time = iterator.next();
            if (time >= currentTime - registerIntervalTime && time <= currentTime) {
                count++;
            } else {
                iterator.remove();
            }
        }
        if (count >= registerMaxCount) {
            response.setStatusCode(HttpStatus.SEE_OTHER);
            String data = "您频繁进⾏注册，请求已被拒绝！";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }

        timeList.add(currentTime);
        ipCacheMap.put(clientIp, timeList);

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
